/**
 * 防重复提交，注意：如果是在function组件中使用，一定要用useCallback包裹起来，否则每次重新渲染，这个方法也会重新初始化
 * @param method 具体执行的方法
 * @param wait 重复提交间隔
 * @param immediate 是否立即执行
 * @returns {function(...[*]=): Promise<any>}
 */
export function debounce(method, wait, immediate) {
    let timeout;
    let debounced = function (...args) {
        let context = this;
        if (timeout) {
            clearTimeout(timeout)
        }
        if (immediate) {
            let callNow = !timeout;
            timeout = setTimeout(() => {
                timeout = null
            }, wait);
            if (callNow) {
                method.apply(context, args);
            }
        } else {
            timeout = setTimeout(() => {
                method.apply(context, args);
            }, wait)
        }
    };
    debounced.cancel = function () {
        clearTimeout(timeout);
        timeout = null
    };
    return debounced
}


export function HttpGet(url) {
    return fetch(url)
        .then(res => res.json()).catch(err => console.error('Error:', err));
}

export function Get(url) {
    return fetch(url)
        .then(res => res.text()).catch(err => console.error('Error:', err));
}

export function HttpPost(url, data) {
    return fetch(url, {
        body: JSON.stringify(data),
        method: 'POST',
        mode: "cors",
        headers: new Headers({
            'Content-Type': 'application/json;charset=utf-8'
        })
    }).then(res => res.json()).catch(err => console.error('Error:', err));
}
